package zhongbo.javaweb.instagram.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import zhongbo.javaweb.instagram.dto.EmailDto;

import java.util.regex.Pattern;

/**
 * 说明：邮件发送服务
 *
 * @author 钟波dellNotebook
 * @since 2022年02月21日 星期一 21:50:56
 */
@Service
@Slf4j
public class EmailService {

    @Value("${spring.mail.username}")
    private String username;

    private final Pattern mailRegx = Pattern.compile("^([a-z0-9A-Z]+[-|.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$");

    @Autowired
    private JavaMailSender javaMailSender;

    public boolean sendMail(EmailDto emailDto) {
        if (emailDto != null) {
            String to = emailDto.getTo();
            if (to == null) {
                throw new RuntimeException("收件人地址不能为空");
            }
            boolean matches = mailRegx.matcher(to).matches();
            if (!matches) {
                throw new RuntimeException("错误的收件人地址:" + to);
            }
            String content = emailDto.getContent();
            if (content == null) {
                throw new RuntimeException("邮件内容不能为空");
            }
            SimpleMailMessage message = buildMailMessage(emailDto);
            javaMailSender.send(message);
            return true;
        }
        throw new RuntimeException("邮件内容未填写");
    }

    private SimpleMailMessage buildMailMessage(EmailDto emailDto) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(emailDto.getTo());
        message.setFrom(username);
        message.setSubject(emailDto.getTitle());
        message.setText(emailDto.getContent());
        return message;
    }
}
